package com.carbohydrate42.kotlin_compose_demo.util

import android.content.Context
import com.carbohydrate42.kotlin_compose_demo.MainApplication
import com.google.gson.Gson

object SharedPreferenceUtil {

    private const val sharedPreferencesFileName = "mes_app_demo"

    private var sharedPreferences = MainApplication.getContext()
        .getSharedPreferences(sharedPreferencesFileName, Context.MODE_PRIVATE)


    fun getInt(key: String): Int {
        return sharedPreferences.getInt(key, -1)
    }

    fun setInt(key: String, value: Int) {
        with(sharedPreferences.edit()) {
            putInt(key, value)
            apply()
        }
    }


    fun getString(key: String): String? {
        return sharedPreferences.getString(key, null)
    }

    fun setString(key: String, value: String) {
        with(sharedPreferences.edit()) {
            putString(key, value)
            apply()
        }
    }

    fun setObject(key: String, obj: Any?) {
        with(sharedPreferences.edit()) {
            putString(key, Gson().toJson(obj))
            apply()
        }
    }

    fun <T> getObject(key: String, clazz: Class<T>): T? {
        val json = getString(key)

        return if (json.isNullOrEmpty())
            null
        else try {
            Gson().fromJson(json, clazz)
        } catch (e: Exception) {
            null
        }
    }

}